package com.dingding.service;

import com.dingding.common.Constants;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

@Slf4j
@Service
@RequiredArgsConstructor(onConstructor_ = @Autowired)
public class RedisService {

    @Autowired
    @Qualifier("redisTemplate")
    private RedisTemplate redisTemplate;

    public void setToken(Long userId, String token) {
        redisTemplate.opsForValue().set(String.format(Constants.REDIS_KEY_TOKEN, userId), token, 1, TimeUnit.DAYS);
    }

    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }

    public void delKey(String key) {
        redisTemplate.delete(key);
    }

    public boolean setCaptch(String uuid, String captch) {
        String key = String.format(Constants.REDIS_KEY_CAPTCH, uuid);
        try {
            redisTemplate.opsForValue().set(key, captch, 5, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            log.error("Failed save captch to redis", e);
            return false;
        }
    }

    public void delCaptch(String uuid) {
        String key = String.format(Constants.REDIS_KEY_CAPTCH, uuid);
        delKey(key);
    }

    public void delVerifyCode(String phone) {
        String key = String.format(Constants.REDIS_KEY_VERIFICATION_CODE, phone);
        delKey(key);
    }

    public String getCaptch(String uuid) {
        String key = String.format(Constants.REDIS_KEY_CAPTCH, uuid);

        Object obj = redisTemplate.opsForValue().get(key);
        return Objects.nonNull(obj) ? obj.toString() : null;
    }

    public boolean setVerificationCode(String phone, String code, int expireMin) {
        String key = String.format(Constants.REDIS_KEY_VERIFICATION_CODE, phone);
        String cntKey = String.format(Constants.REDIS_KEY_VERIFICATION_CNT, phone, code);
        try {
            redisTemplate.opsForValue().set(key, code, expireMin, TimeUnit.MINUTES);
            redisTemplate.opsForValue().set(cntKey, 5, expireMin, TimeUnit.MINUTES);
            return true;
        } catch (Exception e) {
            log.error("Failed save verification code to redis", e);
            return false;
        }
    }

}
